package com.datasource.service;

import com.datasource.entity.OrderDO;
import com.datasource.entity.UserDO;
import com.datasource.mapper.OrderMapper;
import com.datasource.mapper.UserMapper;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author ytj
 * @date 2021/12/14
 */
@Service
public class OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private UserMapper userMapper;

    private OrderService self(){
        return (OrderService) AopContext.currentProxy();
    }


    public void method1(){
        OrderDO orderDO = orderMapper.selectById(1);
        System.out.println(orderDO);
        UserDO userDO = userMapper.selectById(1);
        System.out.println(userDO);
    }


    @Transactional
    public void method2(){
        OrderDO orderDO = orderMapper.selectById(1);
        System.out.println(orderDO);
        UserDO userDO = userMapper.selectById(1);
        System.out.println(userDO);
    }

    public void method3(){
        self().method31();
        self().method32();
    }


    @Transactional
    public void method31(){
        OrderDO orderDO = orderMapper.selectById(1);
        System.out.println(orderDO);
    }

    @Transactional
    public void method32(){
        UserDO userDO = userMapper.selectById(1);
        System.out.println(userDO);
    }


    /**
     * 执行正常
     * transaction开启事务之后在一个事务执行结束之后会和当前线程解绑，
     * 使用的都是方法上面DS指定的数据源，添加在mapper上的数据源失效
     * */
    public void method4(){
        self().method41();
        self().method42();
    }

    @Transactional
    public void method41(){
        OrderDO orderDO = orderMapper.selectById(1);
        System.out.println(orderDO);
    }

    @Transactional
    public void method42(){
        UserDO userDO = userMapper.selectById(1);
        System.out.println(userDO);
    }

    @Transactional
    public void method5(){
        OrderDO orderDO = orderMapper.selectById(1);
        System.out.println(orderDO);
        self().method51();
    }

    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void method51(){
        UserDO userDO = userMapper.selectById(1);
        System.out.println(userDO);
    }
}
